package router

import (
	"art-man-syserr/hanlder"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
func Init() *gin.Engine {
	// 1.创建路由
	r := gin.Default()
	r.Use(Cors()) //默认跨域
	r.Static("/static", "./static")
	// 2.绑定路由规则，执行的函数
	// gin.Context，封装了request和response
	r.POST("login", hanlder.Login)
	r.GET("list", hanlder.List)
	r.GET("list1", hanlder.List1)
	r.GET("list2", hanlder.List2)
	// 3.监听端口，默认在8080
	// Run("里面不指定端口号默认为8080")
	r.Run(":8000")
	return r
}
